// By Robalo / TPWCAS

//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "aisuppress\fn_findCover.sqf"
#include <core_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_unit","_status","_cover","_allcover","_objects","_shooter","_lineIntersect","_terrainIntersect","_inCover","_coverPosition","_cPos","_vPos","_dz","_dx","_last_fired"];

_unit = _this select 0;
_status = _this select 1;

_cover = [];
_allcover = [];
_inCover = false;
[_unit] call FUNC(addSphere);

_unit setVariable [QGVAR(SEARCH_COVER),time];

//potential cover objects list
//_objects = [((nearestObjects [_unit, [], tpwcas_coverdist]) - ((getPosATL _unit) nearRoads tpwcas_coverdist)), {_x call fnc_filter}] call BIS_fnc_conditionalSelect;
_objects = [ (nearestObjects [_unit, ["All"], GVAR(COVER_DISTANCE)]), { _x call FUNC(filterObjects)} ] call BIS_fnc_conditionalSelect;

if ( count _objects > 0 ) then {
	TRACE_1("Found covers",ARR_2(_unit,count _objects));
	// check if current location of unit already provides cover from shooter
	_shooter = _unit getVariable [QGVAR(LAST_SHOOTER),objNull];
	_lineIntersect = lineIntersects [eyePos _shooter, getPosASL _unit, _shooter];

	if !(_lineIntersect) then {	
		_vPos = (vectorDir _shooter);
		TRACE_1("Cover objects for unit %1 found: %2",ARR_2(_unit, _objects));
		{
			if !(_inCover) then {
				//_x is potential cover object
				_bbox = boundingBoxReal _x;
				_dz = abs(((_bbox select 1) select 2) - ((_bbox select 0) select 2));//height
				_dx = abs(((_bbox select 1) select 0) - ((_bbox select 0) select 0));//width
				
				_cPos = (getPosATL _x);
				
				//set coverposition to 1.5 m behind the found cover
				_coverPosition = [((_cPos select 0) + (1.5 * (_vPos select 0))), ((_cPos select 1) + (1.5 * (_vPos select 1))), (_cPos select 2)];
				
				//Any object which is high and wide enough is potential cover position, excluding water
				if ( (_dx > 0.60) && (_dz > 0.45) && !(surfaceIsWater _coverPosition)) then	{
					if ( ( _coverPosition distance _unit ) < 1 )  exitWith {
						TRACE_1("Already has cover",ARR_2(_unit, _coverPosition));
						_inCover = true;
					};
					_cover set [count _cover, [_x, _coverPosition, _dx, _dz]];
					TRACE_1("Adding cover",ARR_2(_unit, _coverPosition));
				};
			};
		} count _objects;
	} else {
		TRACE_1("Already in cover",_unit);
		_inCover = true;
	};
} else {
	TRACE_1("No cover nearby",_unit);
};

//if cover found order unit to move into cover
if (((count _cover) > 0) && !(_inCover)) then {
	[_unit,[0,1,0]] call FUNC(setSphereColor);
	[_unit, _cover select 0, _shooter] spawn FUNC(moveToCover);
} else {
	if (_inCover) then {
		[_unit,[0,0,1]] call FUNC(setSphereColor);
	} else {
		[_unit,[1,0.95,0]] call FUNC(setSphereColor);
		// trigger evasive movement
		[_unit] call FUNC(evasiveMove);
	};
};
TRACE("End");
TMFPROFILERSTOP;
